package com.easyidea.its.domain.service.base.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;

import org.hibernate.SessionFactory;

import com.easyidea.its.domain.model.BaseEntity;
import com.easyidea.its.domain.repository.base.BaseRepository;
import com.easyidea.its.domain.service.base.BaseService;

public class BaseServiceImpl<T extends BaseEntity> implements BaseService<T> {
	/**
	 * session factory
	 */
	protected SessionFactory sessionFactory;

	private BaseRepository<?> baseRepository;

	private Class<T> claz;

	@SuppressWarnings("unchecked")
	public BaseServiceImpl() {
		this.claz = (Class<T>) ((ParameterizedType) getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];
	}

	/**
	 * @return the baseRepository
	 */
	public BaseRepository<?> getBaseRepository() {
		return baseRepository;
	}

	/**
	 * @param baseRepository
	 *            the baseRepository to set
	 */
	public void setBaseRepository(BaseRepository<?> baseRepository) {
		this.baseRepository = baseRepository;
	}

	public T getBeanById(int id) {
		return getBaseRepository().getBeanById(this.claz, id);

	}

	public void removeBean(int id) {
		getBaseRepository().removeBean(this.claz, id);

	}

	public void removeBeanByLogic(int id) {
		getBaseRepository().removeBeanByLogic(this.claz, id);

	}

	public Object save(Object bean) {
		// TODO Auto-generated method stub
		return this.getSessionFactory().getCurrentSession().save(bean);
	}

	public void update(Object bean) {
		this.getSessionFactory().getCurrentSession().update(bean);

	}

	/**
	 * @return the sessionFactory
	 */
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
	 * @param sessionFactory
	 *            the sessionFactory to set
	 */
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public void saveOrUpdateBean(T bean) {
		this.getSessionFactory().getCurrentSession().saveOrUpdate(bean);
	}

	public boolean isRepeated(String propertyName, String propertyValue, Serializable id,boolean isIncludeDeleted) {
		if (id == null) {
			id = Integer.valueOf(0);
		}

		return getBaseRepository().isRepeated(propertyName, propertyValue,
				id, isIncludeDeleted);
	}	
}
